.pragma library

var current_city = "北京";

var citys_return_target = 1;

var current_city_id = "646";

var current_lat = 0

var current_long = 0

var location_key = "4DJIHsuFkH8ZIpn25d39";

// 打开数据库连接
function openDB(){
    return openDatabaseSync("AutohomeDB", "1.0", "Autohome DB", 1000000);
}

function updateCurrentCigy(cityId, cityName){
    current_city = cityName;

    current_city_id = cityId;
    return _doInTransaction(
        function(tx) {
                    var rs = tx.executeSql('SELECT cityId, cityName FROM City where id=?', [1]);
                    if(rs.rows.length <= 0){
                        var rs1 = tx.executeSql('INSERT INTO City VALUES(?, ?, ?)', [ 1, cityId, cityName ]);
                        console.log("insert into city with value:"+cityId+" , "+cityName);
                        if(rs1.insertId > 0){
                            return true;
                        }
                    }else{
                        var rs2 = tx.executeSql('UPDATE City SET cityId=?, cityName=? where id=?', [cityId, cityName, 1]);
                        console.log("update city with value:"+cityId+" , "+cityName);
                        return rs2.rowsAffected > 0;
                    }
        }
    );
}

/**
  *
  */
function _doInTransaction(transactionFunc) {
    try{
        var db = openDB();
        db.transaction(
            function(tx) {
                        // Create the database if it doesn't already exist
                        tx.executeSql('CREATE TABLE IF NOT EXISTS City(id NUMBER UNIQUE, cityId TEXT, cityName TEXT)');
                        return transactionFunc(tx) ;
            }
        )
    }catch(e){
        console.log("City DB ERROR:" + e);
        return false;
    }
}

function syncCurrentCity(){
    return _doInTransaction(
        function(tx) {
                    var rs = tx.executeSql('SELECT cityId, cityName FROM City where id=?', [1]);
                    if(rs.rows.length > 0){
                        current_city = rs.rows.item(0).cityName;
                        current_city_id = rs.rows.item(0).cityId;
                    }
                }

        );
}


function getCityFromGPS(){
    console.log("gps lat:"+current_lat);
    console.log("gps long:"+current_long);
    return "http://loc.desktop.stg.maps.svc.ovi.com/geocoder/rgc/2.0?lat="+current_lat+"&long="+current_long+"&output=xml&lg=chi&referer=api.maps.ovi.com&token="+location_key;
}

function getCitys() {
    return "http://sp.autohome.com.cn/Nokia/CityList.ashx?type=1";
}

function getCurrentCityName(){
    return current_city;
}

function getCurrentCityId(){
    console.log("city id is:"+current_city_id);
    return current_city_id;
}


